﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using AmiDraw.Lib.Models;

namespace AmiDraw.Lib.Factory
{
    public class DrawFactory
    {
        /// <summary>
        /// 获取一张卡。
        /// </summary>
        /// <param name="packName"></param>
        /// <param name="guaranteed"></param>
        /// <returns></returns>
        public static DrawResult Draw(string packName, bool guaranteed, ResultQueryMode mode)
        {
            var packDir = PathFactory.GetPackPath(packName, mode);

            AcPackInfo packInfo = JsonFactory.LoadJson<AcPackInfo>(
                Path.Combine(packDir, "info.json"));

            List<AcLevel> collections = JsonFactory.LoadJson<List<AcLevel>>(
                Path.Combine(packDir, "collections.json"));

            if (guaranteed && collections.Exists(x => x.IsGuaranteed))
            {
                collections = collections.FindAll(x => x.IsGuaranteed).ToList();
            }

            Debug.WriteLine("等级集合数量:" + collections.Count);

            List<(int index, int min, int max)> records = new();
            int min = 0;
            for (var index = 0; index < collections.Count; index++)
            {
                var ratio = collections[index].Ratio;
                records.Add(new(index, min, min + ratio));
                // Debug.WriteLine($"增加范围域 index:{index},min{min}max{}");

                min += ratio;
            }

            var sum = collections.Sum(x => x.Ratio);

            var random = RandomUtil.Number(0, sum - 1);

            var collection = collections[records.Find(x =>
                random >= x.min && random < x.max
            ).index];

            var cardlist = ToCardList(collection.Cards);

            var _collection = (AcLevel)collection.Clone();
            _collection.Cards?.Clear();

            return new DrawResult()
            {
                PackInfo = packInfo,
                CardInfo = cardlist[RandomUtil.Number(0, cardlist.Count - 1)],
                LevelInfo = _collection,
                SumRatio = sum
            };
        }


        private static List<AcCard> ToCardList(List<AcCard> cards)
        {
            var list = new List<AcCard>();
            foreach (var card in cards)
            {
                for (int i = 0; i < card.ExtraProbability + 1; i++)
                {
                    list.Add(card);
                }
            }

            return list;
        }
    }
}